from django.shortcuts import render

# Create your views here.

from QQLoginTool.QQtool import OAuthQQ
from rest_framework import status
from rest_framework.response import Response

from rest_framework.views import APIView

import oauth
from mall import settings
from oauth.models import OAuthQQUser
from oauth.utils import generate_openid_token


class QQView(APIView):
    oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                    redirect_uri=settings.QQ_REDIRECT_URI, state=next)
    def get(self,request):
        #  路径: GET/oauth/qq/statues/?state=xxx

        oauth=self.oauth
        login_url = oauth.get_qq_url()
        return Response({'auth_url':login_url})
        pass

# 扫描后前端获取code,
# 请求方式： GET /oauth/qq/users/?code=xxx
class OauthQQView(APIView):

    def get(self,request):
        #     获取code
        code = request.query_params.get('code')
        # 可能获取不到code
        if not code:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        try:
            # 根据code生token
            token=oauth.get_access_token(code)
            # 根据token生openid
            openid=oauth.get_open_id(token)


        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        try:
            # 如果openid,查询数据库
            qquser=OAuthQQUser.objects.get(openid=openid)


            # 不存在返回绑定页面
        except OAuthQQUser.DoesNotExist:

            # 加密openid
            token_itsdangerous=generate_openid_token(openid)

            data={
                'access_token':token_itsdangerous
            }
            return Response(data)
            pass
        else:
            # 通过qquser外键获取到user
            user=qquser.user

            # 存在,返回首页,登录成功,jwt登录,返回token
            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token1 = jwt_encode_handler(payload)
            data={
                'token':token1,
                'username':user.username,
                'user_id':user.id
            }
            return Response(data=data)
            pass






    pass